#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "freertos/timers.h"
#include "esp_wifi.h"
#include "esp_wpa2.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_smartconfig.h"
#include "nvs_storage.h"
#include "smart_config.h"

#include "server.h"
#include "wifi_connect.h"

/* The event group allows multiple bits for each event,
   but we only care about one event - are we connected
   to the AP with an IP? */
static const char *TAG = "smartconfig";

static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD) {
        ESP_LOGI(TAG, "Got SSID and password");

        smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data;

        uint8_t rvd_data[33] = { 0 };

        ESP_LOGI(TAG, "SSID:%s:::", evt->ssid);
        ESP_LOGI(TAG, "PASSWORD:%s:::",  evt->password);
        if (evt->type == SC_TYPE_ESPTOUCH_V2) {
            ESP_ERROR_CHECK( esp_smartconfig_get_rvd_data(rvd_data, sizeof(rvd_data)) );
            ESP_LOGI(TAG, "RVD_DATA:");
            for (int i=0; i<33; i++) {
                printf("%02x ", rvd_data[i]);
            }
            printf("\n");
        }
        wifi_data_t data;
        memcpy(data.ssid,evt->ssid,sizeof(evt->ssid));
        memcpy(data.password,evt->password,sizeof(evt->password));
        data.ssid_length = sizeof(evt->ssid);
        data.passwd_length = sizeof(evt->password);
        save_wifi_data(data);
        wifi_reinit_sta(data);
    }else if (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE) {
        esp_smartconfig_stop();
        esp_event_handler_unregister(SC_EVENT,ESP_EVENT_ANY_ID,&event_handler);
        start_webserver();
    }
}

void initialise_wifi(void)
{
    ESP_ERROR_CHECK( esp_event_handler_register(SC_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL) );
    ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS) );
    smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_smartconfig_start(&cfg) );
}
